from ninja import Router, Query
from wechatpy import WeChatPay
import xmltodict
from django.utils import timezone

from apps.agent_applets.order.schema import CreateAgentOrderSchema, CreateAgentOrderByTransferSchema, \
    CreateAgentOrderBySpecifySchema
from apps.commom.order import AgentOrderInfoSerializer
from apps.manager.order_info_manager.schemas import ManagerOrderFiltersSchema
from apps.schemas import R
from models.choices import AgentOperationType, WaterCardType
from models.models import AgentOrderInfo, User, WaterCardRecord, WaterCardTransferRecord, AgentPackage
from utils.decorators import handle_exception
from utils.auth import AgentAuthBearer
from water_applets import settings

agent_order_router = Router(tags=["代理订单"], auth=AgentAuthBearer())


@agent_order_router.get("/orders", summary="获取用户代理订单")
@handle_exception("获取用户代理订单失败")
def get_user_orders(request):
    orders = AgentOrderInfo.objects.filter(exec_user=request.user)
    return R.ok(AgentOrderInfoSerializer(data=orders, many=True).data)


@agent_order_router.get("/order/get_district_contact", summary="获取代理商联系方式")
@handle_exception("获取代理商联系方式失败")
def get_agent_order(request, data: ManagerOrderFiltersSchema = Query(...)):
    order = AgentOrderInfo.objects.filter(**data.dict()).first()
    user = User.objects.get(id=order.exec_user.id)
    return R.ok({"phone_number": user.phone_number})


@agent_order_router.post("/order/buy", summary="创建直接购买的代理订单")
@handle_exception("创建直接购买的代理订单失败")
def create_agent_order(request, data: CreateAgentOrderSchema):
    if AgentOrderInfo.objects.filter(**data.dict()).exists():
        return R.fail("该区域已存在代理")
    create_data = data.dict()
    create_data["exec_user"] = request.user
    AgentOrderInfo.objects.create(**create_data)
    request.user.agent_type_id = data.package_id
    return R.ok(msg="创建成功")


@agent_order_router.post("/order/transfer", summary="创建划拨的代理订单")
@handle_exception("创建划拨的代理订单失败")
def create_agent_order(request, data: CreateAgentOrderByTransferSchema):
    user = User.objects.filter(phone_number=data.phone_number).first()
    create_data = {
        "operator": request.user,
        "exec_user": user,
        "transaction_time": timezone.now(),
        "op_type": AgentOperationType.AGENT_OP,
        "water_card_number": data.water_card_number,
    }
    AgentOrderInfo.objects.create(**create_data)
    WaterCardRecord.objects.create(user=user, time=timezone.now(), card_type=WaterCardType.GET,
                                   number=data.water_card_number)
    WaterCardTransferRecord.objects.create(op_user=request.user,
                                           receive_user=user, number=data.water_card_number)
    return R.ok(msg="创建成功")


@agent_order_router.post("/order/specify", summary="创建代理商指定的代理订单")
@handle_exception("创建划拨的代理订单失败")
def create_agent_order(request, data: CreateAgentOrderBySpecifySchema):
    user = User.objects.filter(phone_number=data.phone_number).first()
    normal_agent_package = AgentPackage.objects.filter(name__icontains="普通代理").first()
    create_data = {
        "operator": request.user,
        "exec_user": user,
        "transaction_time": timezone.now(),
        "op_type": AgentOperationType.AGENT_OP,
        "water_card_number": normal_agent_package.water_card_number,
    }
    AgentOrderInfo.objects.create(**create_data)
    WaterCardRecord.objects.create(user=user, time=timezone.now(), card_type=WaterCardType.GET,
                                   number=data.water_card_number)
    WaterCardTransferRecord.objects.create(op_user=request.user,
                                           receive_user=user, number=data.water_card_number)
    return R.ok(msg="创建成功")


@agent_order_router.get("/order/get_pay_id", summary="获取订单支付id")
@handle_exception("获取订单支付id失败")
def get_order_pay_id(request, order_id: int):
    notify_url = f"{settings.WEB_SERVER_IPV4}{+settings.WEB_SERVER_PORT}/applets/order/payment/wxnotify"
    order = AgentOrderInfo.objects.get(order_id=order_id)
    pay = WeChatPay(appid=settings.WECHAT_APPID,
                    api_key=settings.WECHAT_MERCHANT_KEY,
                    sub_appid=settings.WECHAT_APPID,
                    mch_id=settings.WECHAT_MERCHANT_ID)
    response = pay.order.create(trade_type="JSAPI",
                                body=order.good.describe,
                                out_trade_no=order.order_id,
                                user_id=request.user.openid,
                                total_fee=order.package.price * 100,
                                notify_url=notify_url)
    content = xmltodict.parse(response.content)
    if content["return_code"] == 'SUCCESS':
        # 获取预支付交易会话标识
        prepay_id = content.get("prepay_id")
        # 封装返回给前端的数据
        data = {"prepay_id": prepay_id, }
        # order = await OrderInfo.objects.aget(order_id=request.GET.get("out_trade_no"))
        order.transaction_id = prepay_id
        order.transaction_time = timezone.now()
        order.save()
        return R.ok(data)
    else:
        return R.fail("请求支付失败")


@agent_order_router.get("/order/payment/wxnotify", summary="支付结果回调地址")
@handle_exception("支付失败")
def payment_notify(request):
    pay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.WECHAT_MERCHANT_KEY,
                    sub_appid="", mch_id=settings.WECHAT_MERCHANT_ID)
    data = pay.parse_payment_result(request.data)
    order = AgentOrderInfo.objects.get(order_id=data.get("out_trade_no"))
    order.transaction_status = 3
    order.save()
    user = User.objects.get(id=order.exec_user.id)
    user.agent_type = AgentPackage.objects.filter(name__icontains="区域代理").first()
    user.save()
    return R.ok()
